package com.lagou.config;

import com.lagou.pojo.Configuratioin;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.SqlTypeEnum;
import com.mchange.v2.util.CollectionUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * @Description: mapper.xml解析
 * @Author: yw
 * @Date: 2021/7/23 23:35
 **/
public class XMLMpperBuilder {
    
    private Configuratioin configuratioin;

    public XMLMpperBuilder(Configuratioin configuratioin) {
        this.configuratioin = configuratioin;
    }
    
    public void parseMapper(InputStream inputStream) throws Exception{
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String nameSpace = rootElement.attributeValue("namespace");
        List<Element> selectList = rootElement.selectNodes("//select");
        addToMappedStatementMap(nameSpace,selectList,SqlTypeEnum.SELECT);

        List<Element> updateList = rootElement.selectNodes("//update");
        addToMappedStatementMap(nameSpace,updateList,SqlTypeEnum.UPDATE);

        List<Element> insertList = rootElement.selectNodes("//insert");
        addToMappedStatementMap(nameSpace,insertList,SqlTypeEnum.INSERT);

        List<Element> deleteList = rootElement.selectNodes("//delete");
        addToMappedStatementMap(nameSpace,deleteList,SqlTypeEnum.DELETE);
    }

    private void addToMappedStatementMap(String nameSpace,List<Element> elementList,SqlTypeEnum sqlTypeEnum){
        if(null == elementList || elementList.size() == 0){

        }
        MappedStatement mappedStatement = null;
        for(Element element:elementList){
            mappedStatement = new MappedStatement();
            String id = element.attributeValue("id");

            String resultType = element.attributeValue("resultType");
            if(null != resultType){
                mappedStatement.setResultType(resultType);
            }
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();

            mappedStatement.setId(id);
            mappedStatement.setParamType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlTypeEnum(sqlTypeEnum);

            String key = nameSpace+"."+id;
            configuratioin.getMappedStatementMap().put(key,mappedStatement);

        }
    }
}
